<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :forceRender="true"
    switchFullscreen
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="confirmLoading">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <!-- <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :label="$t('reportQuery.supplier')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select :placeholder="$t('reportQuery.selectCustomer')" showSearch
                    :dropdownMatchSelectWidth="false" v-decorator="[ 'organId', validatorRules.organId ]" optionFilterProp="children">
                    <a-select-option v-for="(item,index) in supList" :key="index" :value="item.id">
                      {{ item.supplier }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
          </a-col> -->
          
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['billTime', validatorRules.billTime]" :show-time="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="[ 'billNo' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          
          <!-- 操作员 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')"
              data-step="3" :data-title="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator.trim="['creator']" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" >
              <span>{{$t('popup.documentRemark')}}：</span>
              <a-textarea :rows="1" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="['remark']"
                style="margin-top:8px;width: 88%;" />
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table
          :ref="refKeys[0]"
          :loading="materialTable.loading"
          :columns="materialTable.columns"
          :dataSource="materialTable.dataSource"
          :maxHeight="300"
          :rowNumber="true"
          :rowSelection="false"
          :actionButton="false"
          @valueChange="onValueChange" >
          <template #buttonBefore>
          <a-row :gutter="24" style="float:left;padding-bottom: 5px;" data-step="4"
              :data-title="$t('popup.codeScanningEntry')" :data-intro="$t('popup.thisSupportsGun')">
            
            <a-col :md="6" :sm="24">
              <a-button type="primary" icon="plus" @click="AddDaily()">新增</a-button>
            </a-col>
          </a-row>
          </template>
          </j-editable-table>
        <a-row class="form-row" :gutter="24" >
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('支票收入')">
              <a-input :placeholder="$t('支票收入')" v-decorator.trim="[ 'invoiceTotal' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('现金收入')">
              <a-input :placeholder="$t('现金收入')" v-decorator.trim="[ 'cashTotal' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('银行')">
              <a-input :placeholder="$t('银行收入')" v-decorator.trim="[ 'bankTotal' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('底箱留存金额')">
              <a-input :placeholder="$t('底箱留存金额')" v-decorator.trim="[ 'retainedAmount' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('扣除后总额')">
              <a-input :placeholder="$t('扣除后总额')" v-decorator.trim="[ 'deductAmountTotal' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.enclosure')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="financial"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <person-modal ref="personModalForm" @ok="personModalFormOk"></person-modal>
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import { findBySelectCus, findBySelectSup } from '@/api/api'
  import PersonModal from '../../system/modules/PersonModal'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { FinancialModalMixin } from '../mixins/FinancialModalMixin'
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  import { randomUUID } from "@/utils/util"
  export default {
    name: "AdvanceInModal",
    mixins: [JEditableTableMixin, FinancialModalMixin],
    components: {
      PersonModal,
      JUpload,
      JDate,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    data () {
      return {
        title:this.$t('setailManagement.operation'),
        width: '1600px',
        moreStatus: false,
        supList: [],
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        visible: false,
        model: {},
        fileList:[],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        refKeys: ['accountDataTable', ],
        activeKey: 'accountDataTable',
        materialTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: this.$t('名称'),key: 'name',width: '20%', type: FormTypes.normal, placeholder: this.$t('inPrint.pleaseTnter')+'${title}',fixed:'left',
              props:{class:'defaultColumn-v20230103'},
              allowSearch:true, validateRules: [{ required: true, message:'${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: '', width: '13%', key: 'key', type: FormTypes.hidden, },
          ]
        },
        confirmLoading: false,
        validatorRules:{
          billTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectDocumentDate')+'!' }
            ]
          },
          billTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectDocumentDate')+'!' }
            ]
          },
        },
        url: {
          add: '/dailyHead/addDailyHeadAndDetail',
          edit: '/accountHead/updateAccountHeadAndDetail',
          detailList: '/dailyItem/getDetailList'
        }
      }
    },
    created () {
      
      // this.$refs[this.refKeys[0]].removeRows()
    },
    methods: {
      handleCancel(){
        for (let i = this.materialTable.columns.length - 1; i >=0; i--) {
          let item = this.materialTable.columns[i]
          if(!(item.key === 'name' || item.key === 'id' || item.key === 'key')){
            this.materialTable.columns.splice(i,1)
          }
        }
        this.close()
      },
      AddDaily(){
        this.materialTable.loading = true;
        setTimeout(()=>{
          this.materialTable.loading = false
          this.pushData()
        }, 10);
      },
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        
        this.initSupplier()
        this.billStatus = '0'
        if (this.action === 'add') {
          this.addInit("MRDZB")
          this.fileList = []
          this.$nextTick(() => {
            // this.$refs[this.refKeys[0]].removeRows()
            this.initDatasource()
          });
        } else {
          this.model.operTime = this.model.billTimeStr
          this.model.number = this.model.billNo
          console.log('this.model :>> ', this.model);
          // this.$nextTick(() => {
          //   this.form.setFieldsValue(pick(this.model, ))
          //         this.initDatasource()
          // });
          
          // 加载子表数据
          let params = {
            headerId: this.model.id
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.materialTable);
        }
        this.initRetail()
        this.initPerson()
        // this.initDetailAccount()
      },
      initSupplier() {
        let that = this;
        findBySelectSup({}).then((res)=>{
          if(res) {
            that.supList = res;
          }
        });
      },
      onValueChange(event){
        console.log(event);
        console.log(localStorage.getItem('materialIds'));
        let arr = [
          
        {
              title: this.$t('reportQuery.barcode'), key: 'name', width: '8%', type: FormTypes.popupJsh, kind: 'material', multi: true,
              // validateRules: [{ required: true, message:'${title}'+this.$t('inPrint.cannotTe') }]
            },
        ]
        arr.forEach(val=>{
          this.$set(val,'key',val.key)
        })
        this.materialTable.columns.push(...arr)
      },
      initDatasource(){
        this.materialTable.dataSource = []
        let nameArr =[
          { name: 'S/Total现金总额',  key:'cashAmount'},
          { name: 'KINA EFS（银行）',  key:'bankAmount'},
          { name: 'CHQ(欠款+支票)',  key:'invoiceAmount'},
            {name:'OTHERS',key:'specialAmount'},
            {name:'G/TOTAL',key:'subTotal'},
          { name: 'reading',  key:'readingTotal'},
          { name: 'g.ttl',  key:'ttl'},
            {name:'差额',key:'difference'},
          { name: '底箱金额',  key:'boxAmount'},
          { name: '11-13',  key:'deductAmount'},
          { name: '后台',  key:'device'},

        ]
        this.materialTable.dataSource.splice(0,0,...nameArr)
        let arr = [
          {eachAmount:100,remark:200},
          {eachAmount:100,remark:200},
          {eachAmount:100,remark:200},
          {eachAmount:100,remark:200},
          {eachAmount:100,remark:200},
          {eachAmount:100,remark:200},
          {eachAmount:100,remark:200},
          {eachAmount:100,remark:200},
          {eachAmount:100,remark:200},
          {eachAmount:100,remark:200},
        ]
        
      },
      pushData(){
        let nameArr =[
          { name: 'S/Total现金总额',  key:'cashAmount'},
          { name: 'KINA EFS（银行）',  key:'bankAmount'},
          { name: 'CHQ(欠款+支票)',  key:'invoiceAmount'},
            {name:'OTHERS',key:'specialAmount'},
            {name:'G/TOTAL',key:'subTotal'},
          { name: 'reading',  key:'readingTotal'},
            {name:'credit',key:'discountAmount'},
          { name: 'g.ttl',  key:'ttl'},
            {name:'差额',key:'difference'},
          { name: '后台',  key:'device'},
          { name: '底箱金额',  key:'boxAmount'},
          { name: '11-13',  key:'deductAmount'},
        ]
        let arr = nameArr.map(v=>{
          let obj ={}
          obj[v.key] = parseInt(Math.random() *100)
          return obj
        })
        arr = [Object.assign(...arr)]
        let title = 'POS机' + parseInt(Math.random() *10)
        let key = 'value' + randomUUID()
        console.log('arr :>> ', [Object.assign(...arr)]);
        // dataSource
        arr.forEach(val=>{
            this.materialTable.dataSource.forEach((v,index)=>{
            v[key] = val[v.key]
          })
        })
        
        this.materialTable.columns.push({
              title: title, key: key, width: '8%', type: FormTypes.input, multi: true,
        })
        
        this.$nextTick(()=>{
            this.form.setFieldsValue({ 
              invoiceTotal:123,
              cashTotal:456,
              bankTotal:789,
              retainedAmount:234,
              deductAmountTotal:567
             })
        })
        // this.materialTable.dataSource = this.materialTable.dataSource.map((v,index)=>(v[key] = arr[index][v.key],v))
        this.materialTable.dataSource.push({})
        this.materialTable.dataSource.pop()
      },
      // 计算各总额
      // 计算有多少个value列
      countColumns(object){
        let count = 0
        for (const key in object) {
          if (Object.hasOwnProperty.call(object, key)) {
            if(key.indexOf('value') > -1){
              count++
            }
          }
        }
        return count
      },
      // 得到子表数据
      getColumnsData(array=[]) {
        let rows = []
        array.forEach(val=>{
          let objArr =[]
          for (const k in val) {
            let obj = {}
            if (Object.hasOwnProperty.call(val, k)) {
              if(k.indexOf('value')>-1){
                obj[val.key] = val[k]
                objArr.push(obj)
              }
            }
          }
          rows.push([objArr])
        })
        const length  = this.countColumns(array[0])
        let newArr = []
        for (let index = 0; index < length; index++) {
          let obj = {}
          rows.forEach(val=>{
            obj = Object.assign(obj,val[0][index])
          })
          newArr.push(obj)
        }
        return newArr
      },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        let totalPrice = 0
        let billMain = Object.assign(this.model, allValues.formValue)
        let detailArr = allValues.tablesValue[0].values
        detailArr = this.getColumnsData(detailArr)
        billMain.totalPrice = 0-totalPrice
        billMain.number = billMain.billNo
        billMain.operTime = billMain.billTime
        if(this.model.id){
          billMain.id = this.model.id
        }
        let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        console.log('billMain :>> ', billMain);
        console.log('detailArr :>> ', detailArr);
        return;
        return {
          info: JSON.stringify(billMain),
          attachment: fileList,
          rows: JSON.stringify(detailArr),
        }
      }
    }
  }
</script>
<style>
.input-table .tbody .td .defaultColumn-v20230103{
  color: #409eff!important;
  font-weight: bold;
}
</style>